from tensorflow.keras import layers, models, losses, optimizers, metrics
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import datetime

data = load_iris()
x = data.data
y = data.target

# from tensorflow.keras import utils
# y = utils.to_categorical(y, 3)  #不用sparse损失，必须独热处理

x_train, x_test, y_train, y_test = train_test_split(x, y)
# 设置两层隐藏层，  1层8个神经元   2层6个神经元     relu激活
model = models.Sequential([
    layers.Input(4),  #使用layers.Input指定输入层的单元个数=4
    layers.Dense(8),
    layers.Activation('relu'),
    layers.Dropout(0.3),   #dropout为了防止过拟合，去掉一些单元，去掉30%的单元数
    layers.Dense(6),
    layers.Activation('relu'),
    layers.Dropout(0.3),
    layers.Dense(3, activation='softmax')
])
# 每层添加dropout  0.3 处理

# model.compile(optimizer=optimizers.Adam(0.1),
#               loss=losses.CategoricalCrossentropy(), metrics='accuracy')
#模型编译配置
model.compile(optimizer=optimizers.Adam(0.01),
              loss=losses.SparseCategoricalCrossentropy(), #sparse不用独热
              metrics=[metrics.sparse_categorical_accuracy])

#训练模型：validation_split=0.1表示从x_train/y_train里拿出10%数据作验证集
model.fit(x_train, y_train, validation_split=0.1, epochs=1)

# 打印测试集得分和准确率
score = model.evaluate(x_test, y_test)
print('损失：', score[0])
print('准确率：', score[1])

# import tensorflow as tf
# # 生成tensorboard
# current_time = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
# print(current_time)
# file_path = 'logs/' + current_time
# summary_writer = tf.summary.create_file_writer(file_path)